package com.sss.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @author sss
 * @date 2020-03-07 14:17
 **/
@Service
//@DefaultProperties(defaultFallback = "globalFallbackMethod") //全局降级方法
public class PaymentService {


    //===============服务降级====================
    public String paymentInfo_ok(Integer id){
        return "线程池"+Thread.currentThread().getName()+id+"paymentInfo_ok"+"\tO(∩_∩)O";

    }

    /**
     *   fallbackMethod出场或超时后要调用的方法
     *   commandProperties中的 @HystrixProperty注解中的name代表时间的类型 value设置多长时间为超时
    **/
//    @HystrixCommand(fallbackMethod = "paymentInfo_timeoutHandler",commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
//    })
    public String paymentInfo_timeout(Integer id){
         try {
                     TimeUnit.SECONDS.sleep(4);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
        return "线程池"+Thread.currentThread().getName()+id+"\tpaymentInfo_timeout"+"\t/(ㄒoㄒ)/~~";

    }

    public String paymentInfo_timeoutHandler(Integer id){
        return "线程池"+Thread.currentThread().getName()+id+"\tpaymentInfo_timeoutHandler"+"\t(#`O′)~~";
    }

    public String globalFallbackMethod(Integer id){
        return "Global全局服务降级方法"+"请稍后再试"+"\t(#`O′)~~";
    }

    //===============服务熔断====================
     @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
             @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
             @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
             @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "1000"),//时间窗口期
             @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
     })
     public String paymentCircuitBreaker( Integer id){
        if (id<0){
            throw  new RuntimeException("id 不能为负数");
        }
         String uuid = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t调用成功，流水号为"+uuid;
     }

    public String paymentCircuitBreaker_fallback(Integer id){
        return "服务熔断*******服务繁忙，请稍后重试/(ㄒoㄒ)/~~\tid:"+id;
    }
}
